package com.uwo.house.controller;

import com.uwo.house.beans.request.MessageReq;
import com.uwo.house.beans.response.*;
import com.uwo.house.config.JWTAuthenticationToken;
import com.uwo.house.config.SmsContentConfig;
import com.uwo.house.kits.CacheKits;
import com.uwo.house.kits.SmsKits;
import com.uwo.house.service.IMessageService;
import com.uwo.house.util.UtilDateTime;
import com.uwo.house.util.UtilMisc;
import com.uwo.house.util.UtilReturn;
import com.uwo.house.util.UtilValidate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by YSTen on 2017/7/18.
 */
@Controller
@RequestMapping(value = "/manager")
public class MessageController {

    @Autowired
    private IMessageService messageService;

    /***
     * 根据id获取用户详细信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/message/detail", method = RequestMethod.GET)
    @ResponseBody
    public Map userMessageDetail(HttpServletRequest request) {
        MessageResp messageResp;
        int id;
        if (UtilValidate.isEmpty(request.getParameter("id"))) {
            return UtilReturn.resErrorMap("消息id不能为空", "503");
        } else {
            try {
                id = Integer.parseInt(request.getParameter("id"));
            } catch (Exception e) {
                return UtilReturn.resErrorMap("参数错误", "503");
            }
        }
        try {
            messageResp = messageService.getMessageDetail(id);
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，查询失败！", "503");
        }
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, messageResp);
    }

    /**
     * 消息中心-获取用户消息列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/message", method = RequestMethod.GET)
    @ResponseBody
    public Map userMessageList(@RequestHeader(value = "Authorization") String token,
                               HttpServletRequest request) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        String userId = jwtToken.getUser().getId();
        MessageReq messageReq = new MessageReq();
        List<MessageResp> messageRespList = new ArrayList<MessageResp>();
        messageReq.setUserId(userId);
        try {
            messageRespList = messageService.getAllMessage(messageReq);
            for (MessageResp messageResp : messageRespList) {
                messageResp.setTimeString(UtilDateTime.timeStampToString(messageResp.getMessageTime()));
            }
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，查询失败！", "503");
        }
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, messageRespList);
    }

    /**
     * 消息中心-删除消息
     *
     * @param messageReq
     * @return
     */
    @RequestMapping(value = "/message", method = RequestMethod.DELETE)
    @ResponseBody
    public Map deleteUserMessage(@RequestBody MessageReq messageReq) {
        if (0 == messageReq.getId()) {
            return UtilReturn.resErrorMap("消息id不能为空", "503");
        }
        int count = 0;
        try {
            count = messageService.deleteMessage(messageReq.getId());
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，删除失败！", "503");
        }
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, null);
    }

    /**
     * 添加消息
     *
     * @param messageReq
     * @return
     */
    @RequestMapping(value = "/message", method = RequestMethod.POST)
    @ResponseBody
    public Map saveUserMessage(@RequestBody MessageReq messageReq,
                               @RequestHeader(value = "Authorization") String token) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        String userId = jwtToken.getUser().getId();
        messageReq.setUserId(userId);
        Map resMap;
        if ("1".equals(messageReq.getMessageType())) {
            try {
                messageService.saveMessageForMaintain(messageReq);
            } catch (Exception e) {
                return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
            }
        } else if ("2".equals(messageReq.getMessageType())) {
            try {
                messageService.saveMessageForComplaint(messageReq);
            } catch (Exception e) {
                return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
            }
        } else {
            return UtilReturn.resErrorMap("消息类型错误！", "503");
        }
        messageService.saveSupplierMessage(messageReq.getId());
        try {
            String managerMobile = messageService.getManagerMobile(messageReq.getOrderId());
            SmsKits.send(SmsContentConfig.maintainRemind, managerMobile);//发送短信提醒
        } catch (Exception e) {
            System.out.print("短信发送出错");
        }
        resMap = UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, "操作成功");
        return resMap;
    }

    /**
     * 更新消息（管理员回复用户消息）
     *
     * @param messageReq
     * @return
     */
    @RequestMapping(value = "/message", method = RequestMethod.PUT)
    @ResponseBody
    public Map updateUserMessage(@RequestBody MessageReq messageReq) {
        Map resMap = UtilMisc.toMap();
        try {
            messageService.updateMessage(messageReq);
            String customerMobile = messageService.getCustomerMobile(messageReq.getId());
            SmsKits.send(SmsContentConfig.maintainRemind, customerMobile);
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
        }
        resMap = UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, null);
        return resMap;
    }

    /**
     * 获取所有投诉对象
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/message/complaint", method = RequestMethod.GET)
    @ResponseBody
    public Map updateUserMessage(HttpServletRequest request) {
        Map resMap = UtilMisc.toMap();
        List<MessageComplaintTypeResp> messageComplaintTypeRespList = new ArrayList<MessageComplaintTypeResp>();
        try {
            messageComplaintTypeRespList = messageService.getAllComplaintResp();
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
        }
        resMap = UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, messageComplaintTypeRespList);
        return resMap;
    }

    /**
     * 后台管理-获取维护/投诉列表
     *
     * @param orderId
     * @param messageType
     * @param handleStatus
     * @return
     */
    @RequestMapping(value = "messages/list", method = RequestMethod.GET)
    @ResponseBody
    public Map getMessagesList(@RequestParam(value = "orderId", required = false) String orderId,
                               @RequestParam(value = "messageType", required = false) String messageType,
                               @RequestParam(value = "handleStatus", required = false) Integer handleStatus) {
        List<MessagesResp> list = this.messageService.getMessagesList(orderId, messageType, handleStatus);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, list);
    }

    /**
     * 后台管理-获取维护/投诉详情
     *
     * @return
     */
    @RequestMapping(value = "messages/detail", method = RequestMethod.GET)
    @ResponseBody
    public Map getMessagesDetail(@RequestParam("id") Integer id,
                                 @RequestParam("orderId") String orderId ) {
        MessageResp messagesDetail = this.messageService.getMessageDetail(id);
        ClientInfoResp clientInfoResp = this.messageService.getClientInfo(messagesDetail.getUserId(),orderId);
        Map map = new HashMap();
        map.put("messagesDetail", messagesDetail);
        map.put("clientInfoResp", clientInfoResp);
        return UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, map);
    }

    /**
     * 获取用户下所有订单列表
     *
     * @return
     */
    @RequestMapping(value = "/order/list", method = RequestMethod.GET)
    @ResponseBody
    public Map getUserOrders(@RequestHeader(value = "Authorization") String token) {
        String[] strs = token.split(" ");
        token = (strs.length == 2) ? strs[1] : null;
        JWTAuthenticationToken jwtToken = (JWTAuthenticationToken) CacheKits.get(token);
        String userId = jwtToken.getUser().getId();
        Map map;
        List<CustomerOrderResp> list;
        try {
            list = messageService.getUserOrders(userId);
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
        }
        map = UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, list);
        return map;
    }

    /**
     * 根据订单获取相关人员列表
     *
     * @return
     */
    @RequestMapping(value = "/staff/list", method = RequestMethod.GET)
    @ResponseBody
    public Map getRelatedStaffs(String orderId) {
        Map map;
        List<StaffResp> list;
        try {
            list = messageService.getRelatedStaffs(orderId);
        } catch (Exception e) {
            return UtilReturn.resErrorMap("系统错误，请联系管理员！", "503");
        }
        map = UtilReturn.resSuccesssMap(UtilReturn.SUCCESS_CODE, UtilReturn.SUCCESS_MESSAGE, list);
        return map;
    }
}
